//
//  CrmMainVC.m
//  New_Runway
//
//  Created by mack on 2018/2/24.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CrmMainVC.h"
#import "CRMListTopView.h"
#import "CustomerfilterView.h"
#import "CrmCustomerCell.h"

#import "CrmCustomerInfoModel.h"
#import "CrmFilterStaffVC.h"
#import "UITableView+FDTemplateLayoutCell.h"

#import "CRMCustomerDetailVC.h"
#import "CrmSortView.h"

@interface CrmMainVC ()

<UITableViewDelegate,
UITableViewDataSource,
UIGestureRecognizerDelegate,
CRMListTopViewDelegate>

@property(nonatomic, strong) UITableView *tableview;
@property (assign, nonatomic) NSInteger pageNo;
@property (nonatomic, strong) NSMutableDictionary *params;
@property (nonatomic, strong) CustomerfilterView *filterView;
//@property (nonatomic, assign) BOOL isShow;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSIndexPath *selectTagOne;
@property (nonatomic, assign) NSIndexPath *selectTagTwo;
@property (nonatomic, assign) NSIndexPath *selectTagThree;
@property (nonatomic, assign) NSIndexPath *selectTagFour;
@property (nonatomic, strong) CrmSortView *sortView;
@property (nonatomic, strong) UIButton *backGroundView;
@property (nonatomic, assign) NSInteger reset;
@property (nonatomic, copy) NSString *peopleName;


@end

@implementation CrmMainVC
-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];

    self.pageNo = 1;
    _params = @{@"pageSize": @15, @"pageIndex": @(self.pageNo), @"shopId": [NRWCarUser sharedUser].shopId, @"orderMode": @"DESC", @"marketId": [NRWCarUser sharedUser].marketId}.mutableCopy;
    [_params addEntriesFromDictionary:self.infoDic];
    [self.view addSubview:self.filterView];
    self.selectTagOne = self.selectTagTwo = self.selectTagThree = self.selectTagFour = [NSIndexPath indexPathForRow:0 inSection:0];  
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self loadCustomerList];
}

- (void)setupUI {
    
    self.navigationBarView.titleLabel.text = self.mainTitle;
    [self.navigationBarView.rightItem setTitle:@"排序" forState:UIControlStateNormal];
    self.view.backgroundColor = kColorWhite();
    
    [self setupTopView];
    
    [self initTableview];
}

- (void)setupTopView {
    
    CRMListTopView *topView = [[CRMListTopView alloc] init];
    topView.listViewType = self.type;
    topView.frame = CGRectMake(0, self.navH, Screen_width, 40);
    topView.delegate = self;
    [topView prepar];
    [self.view addSubview:topView];
}

-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.tableFooterView = DPView();
    _tableview.estimatedRowHeight = 0;
    _tableview.estimatedSectionHeaderHeight = 0;
    _tableview.estimatedSectionFooterHeight = 0;
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    self.tableview.backgroundColor = UIColorHex(0xf5f5f5);
    [self.tableview registerClass:[CrmCustomerCell class] forCellReuseIdentifier:@"CELL"];
    self.tableview.mj_header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downPullRefresh)];
    self.tableview.mj_footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upPullLoadMore)];
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).mas_equalTo(self.navH + 40);
        make.bottom.equalTo(weakSelf.view).mas_equalTo(-self.BotH);
        make.left.right.equalTo(weakSelf.view);
    }];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_width, 10)];
    view.backgroundColor = UIColorHex(0xf5f5f5);
    self.tableview.tableHeaderView = view;
}

-(CustomerfilterView *)filterView{
    if (!_filterView) {
        _filterView = [[CustomerfilterView alloc] init];
        _filterView.frame = CGRectMake(0, self.navH + 40, Screen_width, 0);
        _filterView.userInteractionEnabled = YES;
        _filterView.navH = self.navH;
        _filterView.type = self.type;
        kSelfWeak;
        _filterView.selectedBlock = ^(NSString *typeId, NSInteger tag, NSIndexPath *index){
            if (tag == 0) {
                if ([typeId integerValue] == 0) {
                    [weakSelf.params setObject:@"NEXT_FOLLOW_DATETIME" forKey:@"orderColumn"];
                    
                }else{
                    [weakSelf.params setObject:@"" forKey:@"orderColumn"];
                }
                weakSelf.selectTagOne = index;

            }else if (tag == 1){
                [weakSelf.params setObject:typeId forKey:@"levelId"];
                weakSelf.selectTagTwo = index;

            }else if (tag == 2){
                [weakSelf.params setObject:typeId forKey:@"channelId"];
                weakSelf.selectTagThree = index;

            }else if (tag == 3){
                [weakSelf.params setObject:typeId forKey:@"followState"];
                weakSelf.selectTagFour = index;

            }
            weakSelf.pageNo = 1;
            [weakSelf.params setObject:@(weakSelf.pageNo) forKey:@"pageIndex"];
            [weakSelf loadCustomerList];

        };
        UITapGestureRecognizer * PrivateLetterTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAvatarView:)];
        PrivateLetterTap.numberOfTouchesRequired = 1; //手指数
        PrivateLetterTap.numberOfTapsRequired = 1; //tap次数
        PrivateLetterTap.delegate = self;
        [_filterView addGestureRecognizer:PrivateLetterTap];
    }
    return _filterView;

}
- (void)tapAvatarView: (UITapGestureRecognizer *)gesture{
    [self.filterView defaultViewAnimation:NO];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 90;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CrmCustomerResult *info = self.dataArray[indexPath.row];
    
    CrmCustomerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
    cell.index = indexPath;
    cell.CrmInfo = info;
    cell.showdDistributionBtn = [self.mainTitle isEqualToString:@"新客户待分配"];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CRMCustomerDetailVC *vc = [CRMCustomerDetailVC new];
    CrmCustomerResult *info = self.dataArray[indexPath.row];
    vc.customerName = info.customerInfo.customer.customerName;
    vc.customerShopId = info.customerInfo.customerShopId;
    vc.customerId = info.customerInfo.customerId;
    vc.followState = info.customerInfo.followState;
    vc.cityId = info.customerInfo.customer.cityId;
    vc.provinceId = info.customerInfo.customer.provinceId;
    vc.levelId = info.customerInfo.levelId;
    vc.channelId = info.customerInfo.channelId;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)downPullRefresh{
    self.pageNo = 1;
    [_params setObject:@(self.pageNo) forKey:@"pageIndex"];
    [self loadCustomerList];
}
-(void)upPullLoadMore{
    self.pageNo += 1;
    [_params setObject:@(self.pageNo) forKey:@"pageIndex"];
    [self loadCustomerList];
    
}
-(void)loadCustomerList{

    [SVProgressHUD show];

    NSString *url = [NSString stringWithFormat:@"%@%@", CRMContextApi,customerListApi];

    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:self.params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
   
        CrmCustomerInfoModel *model = [CrmCustomerInfoModel mj_objectWithKeyValues:response];
        if (self.pageNo == 1) {
            [self.dataArray removeAllObjects];
        }
        if (model.code == 1) {
            for (NSDictionary *dic in model.result) {
                CrmCustomerResult *info = [CrmCustomerResult mj_objectWithKeyValues:dic];
                [self.dataArray addObject:info];
                
            }
           
        }
        if (self.dataArray.count == 0) {
            [self.tableview addDefaultViewWithText:@"暂无数据哦！" defaultImageType:DefaultImageTypeNoData];
        }else{
            [self.tableview removeDefaultView];
        }
        [SVProgressHUD dismiss];
        [self.tableview reloadData];
        [self endRefresh];
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        [SVProgressHUD dismiss];
        [self endRefresh];

    }];
    
}
-(void)endRefresh{
    [self.tableview.mj_header endRefreshing];
    [self.tableview.mj_footer endRefreshing];
}
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    NSIndexPath *index = userInfo[@"index"];
    CrmCustomerResult *info = self.dataArray[index.row];

    if ([eventName isEqualToString:@"distribution"]) {
        CrmFilterStaffVC *staffVc = [[CrmFilterStaffVC alloc] init];
        staffVc.customerShopId  = info.customerInfo.customerShopId;
        staffVc.successBlock = ^{
            [self downPullRefresh];
        };
        staffVc.type = kFilterStaffVCTypeDistribute;
        [self.navigationController pushViewController:staffVc animated:YES];

    }else if ([eventName isEqualToString:@"detail"]){
        CRMCustomerDetailVC *detailvc = [[CRMCustomerDetailVC alloc] init];
        detailvc.customerName = info.customerInfo.customer.customerName;
        detailvc.customerShopId = info.customerInfo.customerShopId;
        detailvc.customerId = info.customerInfo.customerId;
        detailvc.followState = info.customerInfo.followState;
        detailvc.cityId = info.customerInfo.customer.cityId;
        detailvc.provinceId = info.customerInfo.customer.provinceId;
        detailvc.levelId = info.customerInfo.levelId;
        [self.navigationController pushViewController:detailvc animated:YES];
        
    }
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//判断如果点击的是tableView的cell，就把手势给关闭了
        return NO;//关闭手势
    }//否则手势存在
    return YES;
}
-(CrmSortView *)sortView{
    if (!_sortView) {
        _sortView = [[CrmSortView alloc] initWithFrame:CGRectMake(Screen_width - 110, self.navH, 90, 80)];
        kSelfWeak;
        _sortView.sortBlock = ^(BOOL isRight) {
            if (isRight == YES) {
                [weakSelf.params setObject:@"ASC" forKey:@"orderMode"];
            }else{
                [weakSelf.params setObject:@"DESC" forKey:@"orderMode"];
            }
            weakSelf.pageNo = 1;
            [weakSelf.params setObject:@(weakSelf.pageNo) forKey:@"pageIndex"];
            [weakSelf loadCustomerList];
            
        };
    }
    return _sortView;
}
-(UIButton *)backGroundView{
    if (!_backGroundView) {
        _backGroundView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, Screen_width, Screen_height)];
        [_backGroundView addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backGroundView;
}
-(void)cancelClick{
    self.sortView.hidden = YES;
    self.backGroundView.hidden = YES;
}
-(void)rightItemClick{
    [self.view addSubview:self.backGroundView];
    [self.view addSubview:self.sortView];
    self.sortView.hidden = NO;
    self.backGroundView.hidden = NO;
}

#pragma mark - topViewDelegate
- (void)topView:(CRMListTopView *)view buttonDidClick:(UIButton *)sender withType:(CRMListTopViewButtonType)type {
    
    kSelfWeak;
    if (type == CRMListTopViewButtonTypeSort) {
        [weakSelf.filterView reloadFilterview:0 indexpath:weakSelf.selectTagOne];
        [weakSelf.filterView defaultViewAnimation:YES];
    } else if (type == CRMListTopViewButtonTypeLevel) {
        [weakSelf.filterView reloadFilterview:1 indexpath:weakSelf.selectTagTwo];
        [weakSelf.filterView defaultViewAnimation:YES];
    } else if (type == CRMListTopViewButtonTypeChannel) {
        [weakSelf.filterView reloadFilterview:2 indexpath:weakSelf.selectTagThree];
        [weakSelf.filterView defaultViewAnimation:YES];
    } else if (type == CRMListTopViewButtonTypeState) {
        [weakSelf.filterView reloadFilterview:3 indexpath:weakSelf.selectTagFour];
        [weakSelf.filterView defaultViewAnimation:YES];
    } else if (type == CRMListTopViewButtonTypeFilter) {
        CrmFilterStaffVC *filterVc = [[CrmFilterStaffVC alloc] init];
        if (self.type == kCRMListViewTypeStaffNotProcessed ||
            self.type == kCRMListViewTypeAllFollowCustomer ||
            self.type == kCRMListViewTypeAllEndCustomer) {
            filterVc.type = kFilterStaffVCTypeFilter;
        } else {
            filterVc.type = kFilterStaffVCTypeFilterNoFollower;
        }
        filterVc.chooseOkBlock = ^(NSMutableDictionary *params,NSInteger reset,NSString *peopleName){
            
            weakSelf.pageNo = 1;
            [weakSelf.params setObject:@(weakSelf.pageNo) forKey:@"pageIndex"];
            [weakSelf.params addEntriesFromDictionary:params];
            weakSelf.reset = reset;
            weakSelf.peopleName = peopleName;
            if (reset == kFilterStaffVCReset) {
                [weakSelf.params removeObjectForKey:@"isArrive"];
                [weakSelf.params removeObjectForKey:@"followerId"];
            }
            if (reset == kFilterStaffVCIsReachAll) {
                [weakSelf.params removeObjectForKey:@"isArrive"];
            }
            [weakSelf loadCustomerList];
        };
        filterVc.reset = weakSelf.reset;
        filterVc.peopleName = weakSelf.peopleName;
        [weakSelf.navigationController pushViewController:filterVc animated:YES];
        [weakSelf.filterView defaultViewAnimation:NO];
    }
}

@end
